package com.gin.retrofit.interceptor

import com.gin.retrofit.annotation.StaticQueries
import com.gin.retrofit.annotation.StaticQuery
import okhttp3.Interceptor
import okhttp3.Response
import retrofit2.Invocation

/**
 * 静态参数拦截器
 * @author BX-Gin
 * @since 2024/2/29 10:31
 */
class StaticQueryInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // 获取retrofit创建Request时在tag中保存的被调用的方法, 如果没获取到则直接返回
        val method = request.tag(Invocation::class.java)?.method() ?: return chain.proceed(request)
        val urlBuilder = request.url.newBuilder()
        // 遍历方法上的注解, 处理其中的自定义注解
        for (annotation in method.annotations) {
            if (annotation is StaticQuery) {
                urlBuilder.addQueryParameter(annotation.key, annotation.value)
            }
            if (annotation is StaticQueries) {
                for (staticParam in annotation.value) {
                    urlBuilder.addQueryParameter(staticParam.key, staticParam.value)
                }
            }
        }
        val newRequest = request.newBuilder().url(urlBuilder.build()).build()
        return chain.proceed(newRequest)

    }
}